<!-- 邮件资源 -->
<template>
  <div>
    <el-row style="background: #fff; ">
      <div class="content parameType" style="width: 100%;margin:0">
        <div class="certification top"  style="width: 100%">
          <div class="toptitle">
            <div class="title">智能群发参数配置</div>
          </div>
          <el-form label-width="220px" v-show="formshow">
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="" label-width="120px">
                <!-- <el-checkbox :true-label="1" :false-label="0" v-model="emailForm.IsOpenAIEMailAD">开启智能邮箱，开启后编写的邮件软文将不再发送，系统使用AI智能生成软文，用户自定义邮箱也会失效</el-checkbox> -->
                <el-radio v-model="emailForm.IsOpenAIEMailAD" :label="1">人工智能软文群发</el-radio>
                <el-radio v-model="emailForm.IsOpenAIEMailAD" :label="2">手工软文群发</el-radio>
                <el-radio v-model="emailForm.IsOpenAIEMailAD" :label="3">终端员工手工发送</el-radio>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="" label-width="120px">
                <el-checkbox :true-label="1" :false-label="0" :disabled="emailForm.IsOpenAIEMailAD !== 1" v-model="emailForm.IsAddDatetimeToTitle">每次发送邮件时，标题头自动增加日期时间</el-checkbox>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="" label-width="120px">
                <el-checkbox :true-label="1" :false-label="0" :disabled="emailForm.IsOpenAIEMailAD !== 1" v-model="emailForm.IsSendAIToDefaultAcount">每次生成的AI软文自动发送给定义好的用户邮箱</el-checkbox>
              </el-form-item>
              <el-form-item label="AI软文指定邮箱:" label-width="150px">
                <el-input v-model="emailForm.SendAIMailToAccount" :disabled="emailForm.IsOpenAIEMailAD !== 1 || emailForm.IsSendAIToDefaultAcount !== 1"  style="width:300px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="" label-width="120px">
                <el-checkbox :true-label="1" :false-label="0" :disabled="emailForm.IsOpenAIEMailAD !== 1" v-model="emailForm.IsCreateReadTraceFlag">增加邮件打开跟踪标识（会增加垃圾邮件概率）</el-checkbox>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="" label-width="120px">
                <el-checkbox :true-label="1" :false-label="0" :disabled="emailForm.IsOpenAIEMailAD !== 1" v-model="emailForm.IsCreateClickTraceFlag">增加邮件链接关注跟踪标识（会增加垃圾邮件概率）</el-checkbox>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="" label-width="120px">
                <el-upload
                  class="upload-demo"
                  action="#"
                  multiple
                  ref="upload"
                  :disabled="emailForm.IsOpenAIEMailAD !== 1"
                  :on-change="filechange"
                  :http-request="uploadFile"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  :limit="5"
                  :on-exceed="handleExceed"
                  :file-list="fileList">
                  <el-button size="small" type="primary" :disabled="emailForm.IsOpenAIEMailAD !== 1">上传群发邮件附件</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="生成软文间隔:">
                <el-input v-model.number="emailForm.CreateAIContentInterval" :disabled=" emailForm.IsOpenAIEMailAD !== 1"  style="width:500px" oninput ="value=value.replace(/[^0-9]/g,'')" :maxlength="10"></el-input>
              </el-form-item>
              <p>（单位秒）</p>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="链接文字:">
                <el-input v-model="emailForm.ClickContentFlag" :disabled="emailForm.IsOpenAIEMailAD !== 1 || emailForm.IsCreateClickTraceFlag === 0"  style="width:500px"></el-input>
              </el-form-item>
              <p>（填空表示不生成）</p>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="链接图片:">
                <el-select
                  clearable
                  :disabled="emailForm.IsOpenAIEMailAD !== 1 || emailForm.IsCreateClickTraceFlag === 0"
                  v-model="emailForm.ClientImageFlag"
                  style="width:500px"
                  placeholder="请选择链接图片">
                  <el-option
                    v-for="item in imgList"
                    :key="item.value"
                    :label="item.Descp"
                    :value="item.URL">
                  </el-option>
                </el-select>
              </el-form-item>
              <p>（填空表示不生成）</p>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <div class="toptitle" style="margin-top:20px">
                <div class="title">智能AI参数</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="产品描述:">
                <el-input v-model="emailForm.ProductName" type="textarea" :autosize="{ minRows: 2, maxRows: 6}" :disabled="emailForm.IsOpenAIEMailAD !== 1"  style="width:500px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="输出邮件使用的语言:">
                <el-select
                  :disabled="emailForm.IsOpenAIEMailAD !== 1"
                  v-model="emailForm.Language"
                  style="width:500px"
                  filterable
                  allow-create
                  default-first-option
                  placeholder="请选择输出邮件使用的语言">
                  <el-option
                    v-for="item in LanguageList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="邮件语气:">
                <el-select
                  :disabled="emailForm.IsOpenAIEMailAD !== 1"
                  v-model="emailForm.TOAdver"
                  style="width:500px"
                  placeholder="请选择输出邮件使用的语言">
                  <el-option label="有说服力" value="有说服力"></el-option>
                  <el-option label="正式商务" value="正式商务"></el-option>
                  <el-option label="尊敬" value="尊敬"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="邮件中必须包含的词汇或语句:">
                <el-input v-model="emailForm.MustAdver" type="textarea" :autosize="{ minRows: 2, maxRows: 6}" :disabled="emailForm.IsOpenAIEMailAD !== 1"  style="width:500px"></el-input>
              </el-form-item>
              <p>（用' , ' 或 ' 、' 或 ' ; ' 或 空格 隔开）</p>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="邮件中不能包含的词汇或语句:">
                <el-input v-model="emailForm.NotMustAdver" type="textarea" :autosize="{ minRows: 2, maxRows: 6}" :disabled="emailForm.IsOpenAIEMailAD !== 1"  style="width:500px"></el-input>
              </el-form-item>
              <p>（用' , ' 或 ' 、' 或 ' ; ' 或 空格 隔开）</p>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <!-- <el-button type="primary" @click="TestMailGlobal(emailForm)"  style="margin-left:670px">测试邮箱</el-button> -->
              <el-button type="primary" icon="el-icon-thumb" @click="SetParamMailGlobal(emailForm)"  style="margin-left:470px;margin-top:10px;">保存</el-button>
            </el-col>
          </el-form>
        </div>
      </div>
    </el-row>
  </div>
</template>
<script>
import { connrequest, downloadfile, uploadfile } from '@/api/firstPage'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import XLSX from 'xlsx'
import { getuuid, parseTime } from '@/utils'
import { load } from 'jszip/lib/object'
import massPostingAccount from './massPostingAccount'
import { getToken } from '@/utils/auth' // get token from cookie
export default {
name:'mailResources',
directives: { elDragDialog },
components: { massPostingAccount },
data() {
  return {
    imgList: [],
    LanguageList: [
      {label: "英语(UK)",  value: "英语(UK)"},
      {label: "英语(US)",  value: "英语(US)"},
      {label: "俄语",  value: "俄语"},
      {label: "日语",  value: "日语"},
      {label: "韩语",  value: "韩语"},
      {label: "中文",  value: "中文"}
    ],
    isTestMail: true,
    correct: '',
    abnormal: '',
    percentage: 0,
    loading: false,
    loadingtext: false,
    emailForm: {},
    emailList: [],
    importList:[],
    fileList: [],
    choseList:[],
    CountrysList: [],
    outCountry: [],
    dialogVisible: false,
    importdialog: false,
    codingDialog: false,
    countryDialog: false,
    classDialog: false,
    formshow:true,
    IsActivePwd: 0,
    rules: {
      // Country: [
      //   { required: true, message: "请选择国家", trigger: 'change'},
      // ],
      // Class: [
      //   { required: true, message: "请选择详细分类", trigger: 'change'},
      // ],
      // HSCode: [
      //   { required: true, message: "请输入海关HS编码", trigger: 'change'},
      // ],
      // OutCountry: [
      //   { required: true, message: "请选择出口商国家", trigger: 'change'},
      // ],
      // InCountry: [
      //   { required: true, message: "请选择进口商国家", trigger: 'change'},
      // ],
    },
    resourceForm: {
      ResType: 1,
      Country: "",
      Class: "",
    },
    Action: 1,
    testmail:''
  }
},
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    // this.getData()
    this.GetParamMailADGlobal() 
    this.GetEMailResList()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    // this.GetEMailSmtpCfg()
  },
  methods: {
    async GetEMailResList(){
      const res = await connrequest('GetEMailResList')
      this.imgList =  res.Data
    },
    openCountryDialog(type){
      this.outCountry = []
      this.countryDialog = true
      this.ChoseCountrytype = type
    },
    submitCounyry(){
      if(this.outCountry.length < 1){
        this.$message.error('请选择国家')
        return false
      }
      switch (this.ChoseCountrytype) {
        case 1:
          this.$set(this.resourceForm, 'Country', this.outCountry[0])
          break;
        case 2:
          this.$set(this.resourceForm, 'OutCountry', this.outCountry[0])
          break;
        default:
          this.$set(this.resourceForm, 'InCountry', this.outCountry[0])
          break;
      }
      this.countryDialog = false
    },
    submitClass(){
      this.classDialog = false
    },
    handleChange(value){
      console.log(value);
    },
    checkChange(node){
      if(node.HSCode){
        this.HsCode = node.HSCodesubmit
      }
    },
    viewClassificationCodes(){
      this.HsCode = ''
      this.codingDialog = true
    },
    submitCode(){
      if(this.HsCode !== ''){
        this.$set(this.resourceForm, 'HSCode', this.HsCode)
      }else{
        this.$message.info('请选择品目编码')
      }
    },
    outCountryClick(country){
      if (this.outCountry.length < 1 && !this.outCountry.includes(country)) {
        this.outCountry.push(country);
      } else if (this.outCountry.includes(country)) {
        let index = this.outCountry.indexOf(country);
        this.outCountry.splice(index, 1);
      } else {
        this.$message.info('请选中不超过一个国家');
      }
    },
    async GetDetailFileContent(){
      const data = {
        Data:{
          FileName: '/school/config/national_flag_img.json'
        }
      }
      const res = await connrequest('GetDetailFileContent', data)
      let array = JSON.parse(res.Data.Content);
      const CountrysList = Object.entries(array).map(([country, flag]) => ({ Country: country, flag: `${process.env.VUE_APP_BASE_API}/national_flag_img/${flag}` }));
      this.CountrysList = [...CountrysList]
    },
    async GetEMailADTask(){
      const res = await connrequest('GetEMailADTask')
      this.tableData = res.Data
    },
    importResources(){
      this.$refs.upfile.click()
    },
    handleSelectionChange(val){
      this.choseList = val
    },
    AccountChange(row){
      let mail = row.split("@")[1]
      this.$set(this.emailForm, 'SmtpServer', this.emailList.find( item => item.Mail === mail)?.SmtpServer || '')
      this.emailchange(this.emailList.find( item => item.Mail === mail))
    },
    async GetEMailSmtpCfg(){
      const res = await connrequest('GetEMailSmtpCfg')
      res.Data = res.Data || []
      res.Data.map(item=>{
        item.value = item.SmtpServer
      })
      this.emailList = [...res.Data]
      let mail = this.emailForm.FromAccount ? this.emailForm.FromAccount.split("@")[1] : ''
      this.emailchange(this.emailList.find( item => item.Mail === mail))
    },
    submitImport(){
      let success = 0
      let flag = 0;
      if(this.choseList.length === 0){
        this.$message.success('请先选择要导入的人员')
        return false
      }
      else{
        this.choseList.map(item=>{
          item.IsOpenSSL = item.IsOpenSSL === '加密' ? 1 : 0
          return item
        })
        this.choseList.forEach(async(item) => {
          let Detail = item
          const data = {
            Data:{
              Action: 1,
              Detail: {
                ...Detail,
                Status: 0
              }
            }
          }
          const res = await connrequest('EditMailAccounts', data)
          flag++
          if(res.Status.StatusCode === 0){
            success++
          }
          if(flag === this.choseList.length){
            this.$message({
              showClose: true,
              duration: 7000,
              type: success == this.choseList.length ? 'success' : 'error',
              message: `导入成功${success}个，失败${this.choseList.length - success}个`
            });
            this.importdialog = false
            this.$refs.upfile.value = ''
            this.getData()
          }
        })
      }
    },
    importdialogclose(){
      this.choseList = []
      this.$refs.upfile.value = ''
    },
    async DownloadFile(){
      const data = {
        Data:{
          FileName: '邮件资源模板.xlsx'
        }
      }
      const res = await downloadfile('DownloadPublicFile', data)
      let blobUrl = window.URL.createObjectURL(new Blob([res]));
      const a = document.createElement('a');
      a.style.display = 'none';
      a.download = '邮件资源模板.xlsx';
      a.href = blobUrl;
      a.click();
    },
    changefile(e){
      this.choseList = []
      // 读取表格文件
      let that = this;
      const files = e.target.files;
      if (files.length <= 0) {
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$message({
          message: "上传格式不正确，请上传xls或者xlsx格式",
          type: "warning"
        });
        return false;
      } else {
        // 更新获取文件名
        that.upload_file = files[0].name;
      }
      const fileReader = new FileReader();
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: "binary"
          });
          const wsname = workbook.SheetNames[0]; //取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
          this.da = [...ws]
          let arr = []
          this.da.map(v => {
            let obj = {}
            obj.Name = v['申请人员']
            obj.Account = v['邮箱']
            obj.Pwd = v['密码（需要开通SMTP一些邮件服务器需要为激活密码）']
            obj.SmtpServer = v['邮箱服务器']
            obj.IsOpenSSL = v['是否加密（0：不加密，1：加密）']
            arr.push(obj)
          })
          this.importList = [...arr]
          this.importList = this.unique(this.importList)  //删除exl的重复数据
          this.tableData.forEach(item => {  //删除和tableData重复数据
            this.importList = this.importList.filter(newitem => {
              return newitem.Account !== item.Account
            })
          })
          const email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
          this.importList = this.importList.filter(item => {
            return email.test(item.Account)
          })
          this.importdialog = true
        } catch (e) {
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    },
    unique(arr){
      var obj = {};
      var newArr = arr.reduce((prev,cur)=>{
        obj[cur.Account] ? '':obj[cur.Account] = true && prev.push(cur);
        return prev
      },[]);
      return newArr
    },
    querySearch(queryString, cb) {
      var restaurants = this.emailList;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    querySearch2(queryString, cb) {
      let arr = []
      for (var i = 1; i <= 24; i++){
        arr.push({value: `${i}:00`})
      }
      var restaurants = arr;
      var results = queryString ? restaurants.filter(this.createFilter2(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter2(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    emailchange(row){
      this.$set(this.emailForm, 'IsOpenSSL', row?.IsOpenSSL || 0)
      this.IsActivePwd = row?.IsActivePwd || 0
    },
    async addResources(){
      if(this.tableData.length >= 10){
        this.$message.info('最大配置10个目标客户群体')
        return false
      }
      await this.receiveInformation()
      this.Action = 1
      this.resourceForm = { ResType: 1}
      this.$nextTick(()=>{
        this.$refs['resourceForm'].clearValidate()
      })
      this.dialogVisible = true
    },
    changeMailGlobal(row){
      this.Action = 2
      this.resourceForm = {...row}
      this.resourceForm.IsOpenSSL = row.IsOpenSSL === '加密' ? 1 : 0
      this.dialogVisible = true
    },
    deleteMailGlobal(row){
      this.Action = 3
      this.resourceForm = {...row}
      this.$confirm('此操作将删除项目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = {
          Data:{
            Action: this.Action,
            Detail: {
              ...this.resourceForm
            }
          }
        }
        const res = await connrequest('EditEMailADTask', data)
        if(res.Status.StatusCode === 0){
          this.$message.success('删除成功')
          this.dialogVisible = false
          this.GetEMailADTask()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    async GetParamMailADGlobal(){
      const res = await connrequest('GetParamMailADGlobal')
      // const testmail = await connrequest('GetParamMailADGlobal')
      // this.testmail = testmail.Data.ToAccount
      this.emailForm = {...res.Data}
      if(res.Data?.Attach?.length > 0){
          res.Data.Attach.map(item => {
          item.name = item.FileName
          return item
        })
      }
      this.fileList = res.Data.Attach
    },
    async receiveInformation(){
      const HSCode = await connrequest('GetHSCode')
      const ExpoClass = await connrequest('GetExpoClass')
      const ExpoCountry = await connrequest('GetExpoCountry')
      this.HSCodeList = this.setTooltip(HSCode.Data)
      this.ExpoClassList = ExpoClass.Data
      this.ExpoCountryList = ExpoCountry.Data
    },
    setTooltip(treeData){
      treeData.forEach(node => {
        if (node.HsCode) {
          node.tooltip = `${node.Name} (品目编码：${node.HsCode})`;
        } else {
          node.tooltip = node.Name;
        }
        if (node.Child) {
          this.setTooltip(node.Child);
        }
      })
      return treeData
    },
    async getData() {
      const res = await connrequest('GetMailDstCustomClass')
      res.Data = res.Data || []
      res.Data.map( item =>{
        item.IsOpenSSL = item.IsOpenSSL === 1 ? '加密' : '不加密'
        item.LastCheckTime = parseTime(item.LastCheckTime)
        return item
      })
      this.tableData = res.Data
    },
    async SetParamMailGlobal(){
      let SendInterval = /^[0-9]*$/ 
      let email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      let regPwd = /^[^\u4e00-\u9fa5 ]{0,}$/
      if(!SendInterval.test(this.emailForm.ExecHours) && this.emailForm.ExecHours* 1 > 24){
        this.$message.error('邮件推广执行时间点只能为小于24的数字')
      }
      else if(!SendInterval.test(this.emailForm.SendInterval)){
        this.$message.error('邮件发送延迟只能为数字')
      }
      else if(this.emailForm.IsSendAIToDefaultAcount === 1 && !this.emailForm.SendAIMailToAccount){
        this.$message.error('AI软文指定邮箱不能为空')
      }
      else if(!email.test(this.emailForm.SendAIMailToAccount)&& this.emailForm.IsOpenAIEMailAD === 1 && this.emailForm.IsSendAIToDefaultAcount === 1){
        this.$message.error('AI软文邮箱格式错误')
      }
      // else if(!SendInterval.test(this.emailForm.MaxCountPerDay)){
      //   this.$message.error('最大发送邮件数量只能为数字')
      // }
      else if(this.emailForm.DefaultEMailAccountFormat === ''){
        this.$message.error('默认邮箱前缀不能为空')
      }else if(this.emailForm.DefaultSMTPServer === ''){
        this.$message.error('默认邮箱服务器不能为空')
      }else if(this.emailForm.DefaultEMailPwd === ''){
        this.$message.error('默认邮箱密码不能为空')
      }else if(!regPwd.test(this.emailForm.DefaultEMailPwd)){
        this.$message.error('默认邮箱密码不能有中文或空格')
      }else if (this.emailForm.ProductName === '' && this.emailForm.IsOpenAIEMailAD !== 0){
        this.$message.error('开启智能邮箱时，产品描述不能为空')
      }else if (this.emailForm.Language === '' && this.emailForm.IsOpenAIEMailAD !== 0){
        this.$message.error('开启智能邮箱时，输出邮件使用的语言不能为空')
      }else if (this.emailForm.TOAdverelse === '' && this.emailForm.IsOpenAIEMailAD !== 0){
        this.$message.error('开启智能邮箱时，邮件语气不能为空')
      }else{
        this.emailForm.ExecHours = this.emailForm.ExecHours * 1
        this.emailForm.SendInterval = this.emailForm.SendInterval * 1 || 0
        this.emailForm.MaxCountPerDay = this.emailForm.MaxCountPerDay * 1 || 0
        const data = {
          Data:{
            ...this.emailForm,
            Attach:this.Attach,
          }
        }
        const res = await connrequest('SetParamMailADGlobal', data)
        if(res.Status.StatusCode === 0){
          this.$message.success('保存成功')
          this.GetParamMailADGlobal()
        }
      }
    },
    submit(){
      this.$refs['resourceForm'].validate(async (valid) => {
        if(valid){
          let isDuplicate = this.tableData.some(obj => {
            return obj.ResType === this.resourceForm.ResType &&
                  obj.Country === this.resourceForm.Country &&
                  obj.Class === this.resourceForm.Class;
          });
          let isDuplicate2 = this.tableData.some(obj => {
            return obj.HSCode === this.resourceForm.HSCode &&
                    obj.ResType === this.resourceForm.ResType &&
                  obj.OutCountry === this.resourceForm.OutCountry &&
                  obj.InCountry === this.resourceForm.InCountry;
          });
          if((isDuplicate && this.resourceForm.ResType === 1) || (isDuplicate2 && this.resourceForm.ResType === 2)){
            this.$message.error('已存在相同的用户群体')
            return false
          }
          let resourceForm = this. resourceForm
          if(resourceForm.ResType === 2 && !resourceForm.HSCode && !resourceForm.OutCountry && !resourceForm.InCountry){
            this.$message.error('请填写海关HS编码或选择进口/出口国家')
            return false
          }
          if(resourceForm.ResType === 2 && resourceForm.HSCode && resourceForm.HSCode.length !== 4){
            this.$message.error('请输入4位数字的海关HS编码')
            return false
          }
          const data = {
            Data:{
              Action: this.Action,
              Detail: {
                ...this.resourceForm,
                TaskID: getuuid()
              }
            }
          }
          const res = await connrequest('EditEMailADTask', data)
          if(res.Status.StatusCode === 0){
            this.Action === 1 ? this.$message.success('添加成功') : this.$message.success('修改成功')
            this.dialogVisible = false
            this.GetEMailADTask()
          }
        }
      })
    },
    async TestMailGlobal(row,status,flag = true){
      // const loading = this.$loading({
      //   lock: true,
      //   text: "加载中……",
      //   background: "rgba(0, 0, 0, 0.7)",
      // });
      const ParamMailGlobal = await connrequest('GetParamMailADGlobal')
      if(!ParamMailGlobal.Data.ToAccount){
        this.$message.error('发送测试邮箱失败，请在邮件通知->参数配置界面配置好接收邮箱再进行测试')
        return false
      }
      this.loading = true
      try{
      let IsOpenSSL
      if(status === 1){
        IsOpenSSL = row.IsOpenSSL
      }
      if(status === 2){
        IsOpenSSL = row.IsOpenSSL === '加密' ? 1 : 0
      }
      const data = {
        Data:{
          FromAccount: row.ToAccount || row.Account,
          Pwd: row.Pwd,
          SmtpServer: row.SmtpServer,
          IsOpenSSL: IsOpenSSL,
          IsAddCorpNameToSendAccount: this.emailForm.IsAddCorpNameToSendAccount,
          SendNickName: this.emailForm.SendNickName,
          ToAccount: this.testmail
        },
        Header: {
          showLoading: flag
        }
      }
      const res = await connrequest('TestMailGlobal', data)
      if(res.Status.StatusCode === 0){
        this.correct++
        this.$message.success('发送测试邮件正常')
      }else{
        this.abnormal++
        this.$message.error('邮箱测试异常，发送测试邮件失败')
      }
      // loading.close()
      this.loading = false
      flag && this.getData()
      }catch(e){
      this.loading = false
        // loading.close()
      }
    },
    async TestAllMailGlobal(){
      this.percentage = 0
      const { tableData } = this
      this.loadingtext = false
      this.correct = 0
      this.abnormal = 0
      // const loading = this.$loading({
      //   lock: true,
      //   text: "加载中……",
      //   background: "rgba(0, 0, 0, 0.7)",
      // });
      let num = 100 / tableData.length
      for (let i = 0; i < tableData.length; i++) {
        if (!this.isTestMail) return
        await this.TestMailGlobal(tableData[i], 2, false)
        this.percentage = this.percentage + num
      }
      // loading.close()
      this.loadingtext = true
      this.getData()
    },
    handleSizeChange(){},
    handleCurrentChange(){},
    filechange(file, fileList){
      let arr = []
      fileList.map(item => {
        arr.push({FileName: item.name, InnerName: item.uid + ''})
      })
      this.Attach = arr
    },
    fileclick(){
      this.$refs.filetemplete.click()
    },
    async uploadFile(file){
      let formData = new FormData();
      formData.append('CmdCode', "UploadEMailAttatch");
      formData.append('FileName', file.file.name);
      formData.append('InnerName', file.file.uid);
      formData.append('file', file.file);
      formData.append('Token', getToken());
      const res = await uploadfile('UploadEMailAttatch',formData)
      if(res.Status.StatusCode === 0) {
        this.$message.success('文件上传成功')
      }
    },
    handlePreview(){},
    async handleRemove(file, fileList) {
      const data = {
        Data:{
          InnerName: file.uid
        }
      }
      const res = await connrequest('DeleteEMailAttach', data)
      if(res.Status.StatusCode === 0){
        this.$message.success('文件删除成功')
      }
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
  },
  beforeDestroy () {
    this.isTestMail = false
  }
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
@import "~@/styles/variables.scss";
.parameType .title{
  border: none !important;
}
.el-progress{
  margin-top: 7px;
  width:100%;
}
.content {
  margin-top: 0;
  width: 800px;
  position: relative;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .title{
    margin-bottom: 10px;
    border: none;
    cursor: pointer;
  }
  ::v-deep .certification{
    .toptitle{
      display: flex;
      // border-bottom: 1px solid #eceff5;
      // align-items: center;
      justify-content: space-between;
      // i{
      //   color: #409EFF;
      //   cursor: pointer;
      // }
    }
    .el-form-item{
      margin-bottom: 10px;
    }
    .el-col{
      display: flex;
      align-items: center;
      p{
        width: 100px;
        display:block;
        color: #aaa;
        font-size: 12px;
        padding-left: 20px;
        white-space: nowrap;
      }
    }
  }
}
.top{
  flex-wrap: nowrap;
}
.btn{
  margin: 20px 0;
  display: flex;
  align-items: center;
  .percentage{
    width: 350px;
    margin-left: 20px;
  }
}
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;
    .name {
      text-overflow: ellipsis;
      overflow: hidden;
      line-height: 14px !important;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }
    .highlighted .addr {
      color: #ddd;
    }
  }
}

.tabclick{
  display: flex;
  height: 20px;
  justify-content: center;
  margin-top: 0px;
  .tabitem{
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content:center;
    padding: 2px 10px;
    width: 90px;
    font-size: 12px;
    color: #bbb;
    border-radius: 4px;
    border: 1px solid #ebeef5;
    margin-right: 10px;
    transform:  perspective(2em) rotateX(-20deg);
    span{
      transform:  perspective(2em) rotateX(10deg);
    }
  }
}
.tabclick :hover{
  background: #f7f7f7;
}



</style>